package database

import (
	"database/sql"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"time"
)

type Configuration struct {
	Host     string `yaml:"Host"`
	Port     int    `yaml:"Port"`
	Database string `yaml:"Database"`
	Username string `yaml:"Username"`
	Password string `yaml:"Password"`
	Charset  string `yaml:"Charset"`
	Prefix   string `yaml:"Prefix"`
	PrintSQL bool   `yaml:"PrintSQL"`
}

func NewMysql(config Configuration) *gorm.DB {
	var (
		conn   string
		err    error
		sqlDb  *sql.DB
		gormDb *gorm.DB
	)
	conn = fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?parseTime=True&loc=Local",
		config.Username,
		config.Password,
		config.Host,
		config.Port,
		config.Database,
	)
	// 设置是否打印sql
	var logMode = logger.Silent
	if config.PrintSQL {
		logMode = logger.Info
	}

	gormDb, err = gorm.Open(mysql.Open(conn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   config.Prefix,
			SingularTable: true,
		},
		Logger: logger.Default.LogMode(logMode),
	})
	if err != nil {
		panic("Connection Mysql Failed :" + err.Error())
	}
	sqlDb, err = gormDb.DB()
	if err != nil {
		panic("Connection Mysql Failed :" + err.Error())
	}
	// 空闲连接池中的最大连接数量
	sqlDb.SetMaxIdleConns(10)
	// 打开的数据库连接的最大数量
	sqlDb.SetMaxOpenConns(100)
	// 设置连接复用时间 5min
	sqlDb.SetConnMaxLifetime(300 * time.Second)

	return gormDb
}
